package com.lenovo.smarttraffic.ui.fragment.PersonalCenter;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lenovo.smarttraffic.R;

import com.lenovo.smarttraffic.database.dao.AccountManagementDatabase;
import com.lenovo.smarttraffic.ui.activity.AccountManagementActivity;

/**
 * A simple {@link Fragment} subclass.
 */
public class ThresholdSettingFragment extends Fragment {


    private View view;
    private TextView textView;
    private AccountManagementDatabase accountManagementDatabase;
    private int balance1;
    private int balance2;
    private int balance3;
    private int balance4;
    private int data;

    public ThresholdSettingFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_threshold_setting, container, false);
        textView = view.findViewById(R.id.threshold_setting_fragment_textview);
        EditText editText = view.findViewById(R.id.threshold_setting_fragment_editview);
        Button button = view.findViewById(R.id.threshold_setting_fragment_button);
        //创建数据库
        accountManagementDatabase = new AccountManagementDatabase(getActivity(), "AccountManage.db", null, 1);
        accountManagementDatabase.getWritableDatabase();
        //显示当前阈值
        showData();
        //每3秒获取数据库1-4号车的余额数据，判断是否低于阈值，若低于则发送消息
        handler.sendEmptyMessage(0x999);

        //设置阈值
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor editor = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE).edit();
                editor.putInt("data", Integer.parseInt(editText.getText().toString()));
                editor.apply();
                showData();
            }
        });
        return view;
    }

    //handler每3秒比较一次余额与阈值
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x999) {
                getDatas();
            }
            handler.sendEmptyMessageDelayed(0x999, 3000);
        }
    };

    //获取数据库1-4号车的余额数据
    public void getDatas() {
        balance1 = 0;
        balance2 = 0;
        balance3 = 0;
        balance4 = 0;
        SQLiteDatabase db = accountManagementDatabase.getWritableDatabase();
        Cursor cursor = db.query("Account", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                if (cursor.getString(cursor.getColumnIndex("carnumber")).equals("辽A10001")) {
                    balance1 = cursor.getInt(cursor.getColumnIndex("balance"));
                } else if (cursor.getString(cursor.getColumnIndex("carnumber")).equals("辽A10002")) {
                    balance2 = cursor.getInt(cursor.getColumnIndex("balance"));
                } else if (cursor.getString(cursor.getColumnIndex("carnumber")).equals("辽A10003")) {
                    balance3 = cursor.getInt(cursor.getColumnIndex("balance"));
                } else if (cursor.getString(cursor.getColumnIndex("carnumber")).equals("辽A10004")) {
                    balance4 = cursor.getInt(cursor.getColumnIndex("balance"));
                }
            }while (cursor.moveToNext());
        }
        //判断余额是否低于阈值
        int values = data;
        if (balance1 < values) {
            sendNotification("辽A10001", balance1, values);
        }
        if (balance2 < values) {
            sendNotification("辽A10002", balance2, values);
        }
        if (balance3 < values) {
            sendNotification("辽A10003", balance3, values);
        }
        if (balance4 < values) {
            sendNotification("辽A10004", balance4, values);
        }
    }

    //发送通知
    public void sendNotification(String carnumber, int balance, int values) {
        try{
            Intent intent = new Intent(getActivity(), AccountManagementActivity.class);
            PendingIntent pi = PendingIntent.getActivity(getActivity(),0, intent,0);
            NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = new NotificationCompat.Builder(getActivity())
                    .setContentTitle("余额不足，请及时充值")
                    .setContentText("车牌号："+carnumber+"　余额："+balance+"　阈值："+values)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.car1))
                    .setContentIntent(pi)
                    .setAutoCancel(true)
                    .build();
            manager.notify(1, notification);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //获取SharedPreferences中存储的值
    public void showData() {
        SharedPreferences pref = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
        data = pref.getInt("data", -1);
        if (data < 0) {
            textView.setText("当前1~4号小车账户余额告警阈值未设置！");
        }else {
            textView.setText("当前1~4号小车账户余额告警阈值为"+ data +"元");
        }
    }

}
